package com.yidi.quartz.service.imp;

import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.core.text.Convert;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.utils.StringUtils;
import com.yidi.quartz.domain.SysJobLog;
import com.yidi.quartz.repository.SysJobLogRepository;
import com.yidi.quartz.service.SysJobLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ：Xn
 * @ClassName: SysJobLogServiceImpl
 * @date ：2021-10-19 9:28
 * @describe ：定时任务调度日志表
 */
@Service
public class SysJobLogServiceImpl extends AbstractBaseService<SysJobLog> implements SysJobLogService {

    @Autowired
    private SysJobLogRepository sysJobLogRepository;

    /**
     * 获取quartz调度器日志的计划任务
     *
     * @param jobLog 调度日志信息
     * @return 调度任务日志集合
     */
    @Override
    public Page<SysJobLog> findByPage(Integer pageNo, Integer pageSize, SysJobLog jobLog) {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "id"));
        Sort sort = Sort.by(orders);
        Pageable pageable = PageRequest.of(pageNo, pageSize, sort);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Page<SysJobLog> page = sysJobLogRepository.findAll((root, query, cb) ->{
            List<Predicate> list = new ArrayList<>();
            list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));

            if(StringUtils.isNotBlank(jobLog.getJobName())) {
                list.add(cb.and(cb.like(root.get("jobName").as(String.class), jobLog.getJobName())));
            }

            if(StringUtils.isNotBlank(jobLog.getJobGroup())) {
                list.add(cb.and(cb.equal(root.get("jobGroup").as(String.class), jobLog.getJobGroup())));
            }

            if(StringUtils.isNotBlank(jobLog.getStatus())) {
                list.add(cb.and(cb.equal(root.get("status").as(String.class), jobLog.getStatus())));
            }

            if(StringUtils.isNotBlank(jobLog.getInvokeTarget())) {
                list.add(cb.and(cb.like(root.get("invokeTarget").as(String.class), jobLog.getInvokeTarget())));
            }

            Map<String, Object> params = jobLog.getParams();
            if(params != null) {
                String beginTime = (String) params.get("beginTime");
                String endTime = (String) params.get("endTime");
                if(StringUtils.isNotBlank(beginTime)) {
                    try {
                        list.add(cb.and(cb.greaterThanOrEqualTo(root.get("createTime"), sdf.parse(beginTime))));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(StringUtils.isNotBlank(endTime)) {
                    try {
                        list.add(cb.and(cb.lessThanOrEqualTo(root.get("createTime"), sdf.parse(endTime))));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        },pageable);

        return page;
    }

    @Override
    public void insertJobLog(SysJobLog log) {
        sysJobLogRepository.save(log);
    }

    /**
     * 批量删除调度日志信息
     *
     * @param jobLogIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    public void deleteJobLogByIds(Long[] jobLogIds)
    {
        for(Long id : jobLogIds) {
            deleteJobLogById(id);
        }
    }

    /**
     * 删除任务日志
     * （物理删除）
     * @param jobLogId 调度日志ID
     */
    @Override
    public void deleteJobLogById(Long jobLogId)
    {
        SysJobLog jobLog = findById(jobLogId);
        if(jobLog != null) {
            jobLog.setRemoveStatus(RemoveEnum.REMOVE.getCode());
            modify(jobLog);
        }
        //delete(jobLogId);
    }

    /**
     * 清空任务日志
     */
    @Override
    public void cleanJobLog()
    {
        List<SysJobLog> all = findAllByRs(RemoveEnum.NOT_REMOVE.getCode());
        for(SysJobLog jl : all) {
            jl.setRemoveStatus(RemoveEnum.REMOVE.getCode());
            modify(jl);
        }
        //deleteAll();
    }
}
